package controller;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import object.TradeAddr;
import object.Transaction;
import object.UserCenter;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import pojo.Commodity;
import pojo.LogIncome;
import pojo.LogNoruserbill;
import pojo.TransactionAddr;
import pojo.TransactionDetails;
import pojo.TransactionLog;
import service.TransactionService;
import sun.misc.BASE64Encoder;
import utils.GetHelper;
import utils.MD5Helper;
import utils.OrderNumUtil;
import config.ConstantConfig;
import config.SysConfig;

/**
 * 
 * @author zgy
 *
 */
@Controller
@RequestMapping("transaction")
public class TransactionController {

	@Autowired
	private TransactionService transactionService;
	
	private static Logger logger = Logger.getLogger(TransactionController.class);
	/**
	 * 0001接口
	 * 下发商品列表
	 * @param curPage
	 * @param pageSize
	 * @param httpRequest
	 * @return
	 */
	@RequestMapping("queryCommodity")
//	@ResponseBody
	public String queryCommodity(
			@RequestParam(value = "curPage", defaultValue = "1") Integer curPage,
			@RequestParam(value = "pageSize", defaultValue = "3") Integer pageSize,
			HttpServletRequest req) {
		List<Commodity> commodities = null;
		try {
			commodities = transactionService.queryCommodity(curPage, pageSize);
			logger.info("商品列表------"+commodities);
			req.setAttribute("responseCode", "00000");
			req.setAttribute("response", ConstantConfig.QUERY_SUCCESS);
			req.setAttribute("commodityList", commodities);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			req.setAttribute("responseCode", "E0001");
			req.setAttribute("response", ConstantConfig.EXCEPTION_OCCURS);
			e.printStackTrace();
		}
		return "forward:/web/index/homeAjax.jsp";
	}
	
	/**
	 * 0002接口
	 * 下发交易地址列表
	 * @param platformId
	 * @param httpRequest
	 * @return
	 */
	@RequestMapping("queryTradeAddr")
//	@ResponseBody
	public String queryTradeAddr(
			@RequestParam("platformId") String platformId,
			HttpServletRequest req) {
		
		List<TradeAddr> tradeAddrs = null;
		
		try {
			tradeAddrs = transactionService.queryTradeAddr(platformId);
			logger.info("交易地址列表------"+tradeAddrs);
			req.setAttribute("responseCode", "00000");
			req.setAttribute("response", ConstantConfig.QUERY_SUCCESS);
			req.setAttribute("tradeAddrList", tradeAddrs);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			req.setAttribute("responseCode", "E0001");
			req.setAttribute("response", ConstantConfig.EXCEPTION_OCCURS);
			e.printStackTrace();
		}
		return "forward:/web/person/addrmanageAjax.jsp";
	}
	
	@RequestMapping("querySingleTradeAddr")
	@ResponseBody
	public HashMap<String, Object> querySingleTradeAddr(
			@RequestParam("platformId") String platformId,
			HttpServletRequest httpRequest) {
		
		HashMap<String, Object> response = new HashMap<>();
		List<TradeAddr> tradeAddrs = null;
		
		try {
			tradeAddrs = transactionService.queryTradeAddr(platformId);
			logger.info("交易地址列表------"+tradeAddrs);
			response.put("responseCode", "00000");
			response.put("response", ConstantConfig.QUERY_SUCCESS);
			response.put("tradeAddrList", tradeAddrs);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			response.put("responseCode", "E0001");
			response.put("response", ConstantConfig.EXCEPTION_OCCURS);
			e.printStackTrace();
		}
		return response;
	}
	
	/**
	 * 0003接口
	 * 交易订单提交
	 * @param platformId
	 * @param receiveAddr
	 * @param sendAndReceiveType
	 * @param receiveOrderTimeStart
	 * @param sendOrderTimeEnd
	 * @param sendOrderTimeStart
	 * @param receiveOrderTimeEnd
	 * @param comment
	 * @param commodityIds
	 * @param goodsNums
	 * @param httpRequest
	 * @return
	 */
	@RequestMapping("commitTransaction")
	@ResponseBody
	public HashMap<String, Object> commitTransaction(
			@RequestParam("platformId") String platformId,
			@RequestParam("receiveAddr") String receiveAddr,
			@RequestParam("sendAndReceiveType") String sendAndReceiveType,
			@RequestParam("receiveOrderTimeStart") Timestamp receiveOrderTimeStart,
			@RequestParam("sendOrderTimeEnd") Timestamp sendOrderTimeEnd,
			@RequestParam("sendOrderTimeStart") Timestamp sendOrderTimeStart,
			@RequestParam("receiveOrderTimeEnd") Timestamp receiveOrderTimeEnd,
			@RequestParam("comment") String comment,
			@RequestParam("commodityIds") String commodityIds,
			@RequestParam("goodsNums") String goodsNums,
			@RequestParam("totalNums") Integer totolNums,
			@RequestParam("totalPrice") BigDecimal totolPrice,
			HttpServletRequest httpRequest) {
		
		HashMap<String, Object> response = new HashMap<>();
		pojo.Transaction transaction = new pojo.Transaction();
		try {
			transaction.setReceiveAddr(java.net.URLDecoder.decode(receiveAddr, "UTF-8"));
			transaction.setSendAndReceiveType(sendAndReceiveType);
			transaction.setReceiveOrderTimeStart(receiveOrderTimeStart);
			transaction.setSendOrderTimeEnd(sendOrderTimeEnd);
			transaction.setSendOrderTimeStart(sendOrderTimeStart);
			transaction.setReceiveOrderTimeEnd(receiveOrderTimeEnd);
			transaction.setStartTime(new Timestamp(System.currentTimeMillis()));
			transaction.setTotalNums(totolNums);
			transaction.setPaymentPrice(totolPrice);
			transaction.setCheck(ConstantConfig.TRANSACTION_CHECK_NO);
			if(BigDecimal.ZERO.compareTo(totolPrice)==0){
				transaction.setPayment(ConstantConfig.TRANSACTION_PAMENT_FREE);
			}else{
				transaction.setPayment(ConstantConfig.TRANSACTION_PAMENT_NOPAY);
			}
			transaction.setOrderNum(OrderNumUtil.createTradeNumber());
			transaction.setStatus(ConstantConfig.TRANSACTION_STATUS_ORDER);
			transaction.setComment(java.net.URLDecoder.decode(comment, "UTF-8"));
			boolean result = false;
			result = transactionService.commitTransaction(transaction,platformId,commodityIds,goodsNums);
			logger.info("交易提交结果------"+result);
			if(result){
				response.put("responseCode", "00000");
				response.put("response", ConstantConfig.INSERT_SUCCESS);
			}else{
				response.put("responseCode", "00001");
				response.put("response", ConstantConfig.INSERT_FAILED);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			response.put("responseCode", "E0001");
			response.put("response", ConstantConfig.EXCEPTION_OCCURS);
			e.printStackTrace();
		}
		return response;
	}
	
	
	/**
	 * 0004接口
	 * 交易订单查询
	 * @param orderNum
	 * @param httpRequest
	 * @return
	 */
	@RequestMapping("queryTransaction")
	@ResponseBody
	public HashMap<String, Object> queryTransaction(
			@RequestParam("platformId") String platformId,
			HttpServletRequest httpRequest) {
		
		HashMap<String, Object> response = new HashMap<>();
		List<Transaction> transactions = null;
		
		try {
			transactions = transactionService.queryTransaction(platformId);
			logger.info("交易订单查询------"+transactions);
			response.put("responseCode", "00000");
			response.put("response", ConstantConfig.QUERY_SUCCESS);
			response.put("transactionList", transactions);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			response.put("responseCode", "E0001");
			response.put("response", ConstantConfig.EXCEPTION_OCCURS);
			e.printStackTrace();
		}
		return response;
	}
	
	/**
	 * 0005接口
	 * 交易订单明细
	 * @param orderNum
	 * @param httpRequest
	 * @return
	 */
	@RequestMapping("queryTransactionDetails")
//	@ResponseBody
	public String queryTransactionDetails(
			@RequestParam("orderNum") String orderNum,
			HttpServletRequest req) {
		
		List<TransactionDetails> transactionDetails = null;
		int totalNum = 0;
		BigDecimal totalPrice = BigDecimal.ZERO;
		try {
			transactionDetails = transactionService.queryTransactionDetail(orderNum);
			logger.info("交易订单详情------"+transactionDetails);
			req.setAttribute("responseCode", "00000");
			req.setAttribute("response", ConstantConfig.QUERY_SUCCESS);
			req.setAttribute("orderNum", orderNum);
			req.setAttribute("transactionDetails", transactionDetails);
			for(TransactionDetails t:transactionDetails){
				totalNum+=t.getGoodsNum();
				totalPrice=totalPrice.add(t.getGoodsPrice().multiply(new BigDecimal(t.getGoodsNum())));
			}
			req.setAttribute("totalNum", totalNum);
			req.setAttribute("totalPrice", totalPrice);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			req.setAttribute("responseCode", "E0001");
			req.setAttribute("response", ConstantConfig.EXCEPTION_OCCURS);
			e.printStackTrace();
		}
		return "forward:/web/order/detailAjax.jsp";
	}
	
	/**
	 * 0006接口
	 * 订单流程跟踪
	 * @param orderNum
	 * @param httpRequest
	 * @return
	 */
	@RequestMapping("queryTransactionLog")
	@ResponseBody
	public HashMap<String, Object> queryTransactionLog(
			@RequestParam("orderNum") String orderNum,
			HttpServletRequest httpRequest) {
		
		HashMap<String, Object> response = new HashMap<>();
		List<TransactionLog> transactionLogs = null;
		
		try {
			transactionLogs = transactionService.queryTransactionLog(orderNum);
			logger.info("交易订单流程------"+transactionLogs);
			response.put("responseCode", "00000");
			response.put("response", ConstantConfig.QUERY_SUCCESS);
			response.put("orderNum", orderNum);
			response.put("transactionLogs", transactionLogs);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			response.put("responseCode", "E0001");
			response.put("response", ConstantConfig.EXCEPTION_OCCURS);
			e.printStackTrace();
		}
		return response;
	}
	
	/**
	 * 0007接口
	 * 个人中心查询
	 * @param platformId
	 * @param httpRequest
	 * @return
	 */
	@RequestMapping("queryUserCenter")
	@ResponseBody
	public HashMap<String, Object> queryUserCenter(
			@RequestParam("platformId") String platformId,
			HttpServletRequest httpRequest) {
		
		HashMap<String, Object> response = new HashMap<>();
		UserCenter userCenter = null;
		
		try {
			userCenter = transactionService.queryUserCenter(platformId);
			byte[] bs=userCenter.getIcon();
			BASE64Encoder encoder = new BASE64Encoder();
			String icon="";
			if(bs!=null){
				icon="data:image/png;base64,"+encoder.encode(bs);
			}
			logger.info("个人中心查询------"+userCenter);
			response.put("responseCode", "00000");
			response.put("response", ConstantConfig.QUERY_SUCCESS);
			response.put("firstName", userCenter.getFirstName());
			response.put("lastName", userCenter.getLastName());
			response.put("mobileNum", userCenter.getMobileNum());
			response.put("icon", icon);
			response.put("balance", userCenter.getBalance());
			response.put("userId", userCenter.getUserId());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			response.put("responseCode", "E0001");
			response.put("response", ConstantConfig.EXCEPTION_OCCURS);
			e.printStackTrace();
		}
		return response;
	}
	
	/**
	 * 0008接口
	 * 交易订单修改
	 * @param orderNum
	 * @param commodityIds
	 * @param goodsNums
	 * @param totolNums
	 * @param totolPrice
	 * @param httpRequest
	 * @return
	 */
	@RequestMapping("updateTrade")
	@ResponseBody
	public HashMap<String, Object> updateTrade(
			@RequestParam("platformId") String platformId,
			@RequestParam("orderNum") String orderNum,
			@RequestParam("commodityIds") String commodityIds,
			@RequestParam("goodsNums") String goodsNums,
			@RequestParam("totolNums") Integer totolNums,
			@RequestParam("totolPrice") BigDecimal totolPrice,
			HttpServletRequest httpRequest) {
		
		HashMap<String, Object> response = new HashMap<>();
		pojo.Transaction transaction = new pojo.Transaction();

		transaction.setOrderNum(orderNum);
		transaction.setTotalNums(totolNums);
		transaction.setPaymentPrice(totolPrice);
		boolean result = false;
		try {
			result = transactionService.updateTransaction(transaction,platformId,commodityIds,goodsNums);
			logger.info("交易修改结果------"+result);
			if(result){
				response.put("responseCode", "00000");
				response.put("response", ConstantConfig.UPDATE_SUCCESS);
			}else{
				response.put("responseCode", "00001");
				response.put("response", ConstantConfig.UPDATE_FAILED);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			response.put("responseCode", "E0001");
			response.put("response", ConstantConfig.EXCEPTION_OCCURS);
			e.printStackTrace();
		}
		return response;
	}
	
	/**
	 * 0009接口
	 * 新增交易地址
	 * @param platformId
	 * @param province
	 * @param city
	 * @param area
	 * @param street
	 * @param addr
	 * @param status
	 * @param mobileNum
	 * @param name
	 * @param httpRequest
	 * @return
	 */
	@RequestMapping("addTradeAddr")
	@ResponseBody
	public HashMap<String, Object> addTradeAddr(
			@RequestParam("platformId") String platformId,
			@RequestParam("province") String province,
			@RequestParam("city") String city,
			@RequestParam("area") String area,
			@RequestParam("street") String street,
			@RequestParam("addr") String addr,
			@RequestParam("status") String status,
			@RequestParam("mobileNum") String mobileNum,
			@RequestParam("name") String name,
			HttpServletRequest httpRequest) {
		
		HashMap<String, Object> response = new HashMap<>();
		pojo.TransactionAddr transactionAddr = new TransactionAddr();
		
		try {
			transactionAddr.setProvince(java.net.URLDecoder.decode(province, "UTF-8"));
			transactionAddr.setCity(java.net.URLDecoder.decode(city, "UTF-8"));
			transactionAddr.setArea(java.net.URLDecoder.decode(area, "UTF-8"));
			transactionAddr.setStreet(java.net.URLDecoder.decode(street, "UTF-8"));
			transactionAddr.setAddr(java.net.URLDecoder.decode(addr, "UTF-8"));
			transactionAddr.setStatus(status);
			transactionAddr.setMobileNum(mobileNum);
			transactionAddr.setName(java.net.URLDecoder.decode(name, "UTF-8"));
			transactionAddr.setAddrType(ConstantConfig.TRANSACTION_ADDRESS_TYPE_SEND);
			
			boolean result = false;
			if("2".equals(status)){
				result=transactionService.clearAddrStatus(platformId);
				logger.info("重置交易地址结果------"+result);
			}
			result = transactionService.insertTradeAddr(transactionAddr,platformId);
			logger.info("新增交易地址结果------"+result);
			if(result){
				response.put("responseCode", "00000");
				response.put("response", ConstantConfig.INSERT_SUCCESS);
			}else{
				response.put("responseCode", "00001");
				response.put("response", ConstantConfig.INSERT_FAILED);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			response.put("responseCode", "E0001");
			response.put("response", ConstantConfig.EXCEPTION_OCCURS);
			e.printStackTrace();
		}
		return response;
	}
	
	
	/**
	 * 0010接口
	 * 修改交易地址
	 * @param addrID
	 * @param province
	 * @param city
	 * @param area
	 * @param street
	 * @param addr
	 * @param status
	 * @param mobileNum
	 * @param name
	 * @param httpRequest
	 * @return
	 */
	@RequestMapping("updateTradeAddr")
	@ResponseBody
	public HashMap<String, Object> updateTradeAddr(
			@RequestParam("platformId") String platformId,
			@RequestParam("addrID") Integer addrID,
			@RequestParam("province") String province,
			@RequestParam("city") String city,
			@RequestParam("area") String area,
			@RequestParam("street") String street,
			@RequestParam("addr") String addr,
			@RequestParam("status") String status,
			@RequestParam("mobileNum") String mobileNum,
			@RequestParam("name") String name,
			HttpServletRequest httpRequest) {
		
		HashMap<String, Object> response = new HashMap<>();
		pojo.TransactionAddr transactionAddr = new TransactionAddr();
		
		try {
			transactionAddr.setAddrId(addrID);
			transactionAddr.setProvince(java.net.URLDecoder.decode(province, "UTF-8"));
			transactionAddr.setCity(java.net.URLDecoder.decode(city, "UTF-8"));
			transactionAddr.setArea(java.net.URLDecoder.decode(area, "UTF-8"));
			transactionAddr.setStreet(java.net.URLDecoder.decode(street, "UTF-8"));
			transactionAddr.setAddr(java.net.URLDecoder.decode(addr, "UTF-8"));
			transactionAddr.setStatus(status);
			transactionAddr.setMobileNum(mobileNum);
			transactionAddr.setName(java.net.URLDecoder.decode(name, "UTF-8"));
			
			boolean result = false;
			if("2".equals(status)){
				result=transactionService.clearAddrStatus(platformId);
				logger.info("重置交易地址结果------"+result);
			}
			result = transactionService.updateTradeAddr(transactionAddr);
			logger.info("修改交易地址结果------"+result);
			if(result){
				response.put("responseCode", "00000");
				response.put("response", ConstantConfig.UPDATE_SUCCESS);
			}else{
				response.put("responseCode", "00001");
				response.put("response", ConstantConfig.UPDATE_FAILED);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			response.put("responseCode", "E0001");
			response.put("response", ConstantConfig.EXCEPTION_OCCURS);
			e.printStackTrace();
		}
		return response;
	}
	
	
	/**
	 * 0011接口
	 * 删除交易地址
	 * @param addrID
	 * @param httpRequest
	 * @return
	 */
	@RequestMapping("deleteTradeAddr")
	@ResponseBody
	public HashMap<String, Object> deleteTradeAddr(
			@RequestParam("addrID") Integer addrID,
			HttpServletRequest httpRequest) {
		
		HashMap<String, Object> response = new HashMap<>();
		pojo.TransactionAddr transactionAddr = new TransactionAddr();
		
		transactionAddr.setAddrId(addrID);
		
		boolean result = false;
		try {
			result = transactionService.deleteTradeAddr(transactionAddr);
			logger.info("删除交易地址结果------"+result);
			if(result){
				response.put("responseCode", "00000");
				response.put("response", ConstantConfig.DELETE_SUCCESS);
			}else{
				response.put("responseCode", "00001");
				response.put("response", ConstantConfig.DELETE_FAILED);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			response.put("responseCode", "E0001");
			response.put("response", ConstantConfig.EXCEPTION_OCCURS);
			e.printStackTrace();
		}
		return response;
	}
	
	/**
	 * 0012接口
	 * 订单完成列表
	 * @param platformId
	 * @param httpRequest
	 * @return
	 */
	@RequestMapping("completeTrade")
//	@ResponseBody
	public String completeTrade(
			@RequestParam("platformId") String platformId,
			@RequestParam(value = "flag", defaultValue = "complete") String flag,
			@RequestParam(value = "orderNum", defaultValue = "null") String orderNum,
			HttpServletRequest req) {
		
		List<Transaction> transactions = null;
		
		try {
			transactions = transactionService.queryCompleteTrade(platformId);
			logger.info("已完成订单列表------"+transactions);
			req.setAttribute("responseCode", "00000");
			req.setAttribute("response", ConstantConfig.QUERY_SUCCESS);
			req.setAttribute("flag", flag);
			req.setAttribute("orderNum", orderNum);
			req.setAttribute("completeTradeList", transactions);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			req.setAttribute("responseCode", "E0001");
			req.setAttribute("response", ConstantConfig.EXCEPTION_OCCURS);
			e.printStackTrace();
		}
		return "forward:/web/order/completedAjax.jsp";
	}
	
	/**
	 * 0014接口
	 * 取消订单
	 * @param orderNum
	 * @param httpRequest
	 * @return
	 */
	@RequestMapping("cancelTrade")
	@ResponseBody
	public HashMap<String, Object> cancelTrade(
			@RequestParam("orderNum") String orderNum,
			HttpServletRequest httpRequest) {
		
		HashMap<String, Object> response = new HashMap<>();
		pojo.Transaction transaction = new pojo.Transaction();
		
		transaction.setOrderNum(orderNum);
		
		boolean result = false;
		try {
			result = transactionService.cancelTransaction(transaction);
			logger.info("取消交易订单结果------"+result);
			if(result){
				response.put("responseCode", "00000");
				response.put("response", ConstantConfig.DELETE_SUCCESS);
			}else{
				response.put("responseCode", "00001");
				response.put("response", ConstantConfig.DELETE_FAILED);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			response.put("responseCode", "E0001");
			response.put("response", ConstantConfig.EXCEPTION_OCCURS);
			e.printStackTrace();
		}
		return response;
	}
	/**
	 * 0015接口
	 * 用户注册验证
	 * @param openid
	 * @param httpRequest
	 * @return
	 */
	@RequestMapping("isUserRegistered")
	@ResponseBody
	public HashMap<String, Object> isUserRegistered(
			@RequestParam("openid") String openid,
			HttpServletRequest httpRequest) {
		
		HashMap<String, Object> response = new HashMap<>();
		
		boolean result = false;
		try {
			result = transactionService.isUserRegistered(openid);
			logger.info("验证用户注册结果结果------"+result);
			if(result){
				response.put("responseCode", "00000");
				response.put("response", ConstantConfig.QUERY_SUCCESS);
			}else{
				response.put("responseCode", "00001");
				response.put("response", ConstantConfig.QUERY_FAILED);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			response.put("responseCode", "E0001");
			response.put("response", ConstantConfig.EXCEPTION_OCCURS);
			e.printStackTrace();
		}
		return response;
	}
	/**
	 * 0016接口
	 * 获取微信openid
	 * @param code
	 * @param req
	 * @return
	 */
	@RequestMapping("getOpenID")
	@ResponseBody
	public String getOpenID(
			@RequestParam("code") String code,
			HttpServletRequest req) {
		String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx95addf674a498ab9&secret=5aee0421f9ac8f330692371b03fa12c3&code="+code+"&grant_type=authorization_code";
		return GetHelper.doHttpGet(url);
	}
	
//======================================微信相关方法===========================================	
	
	/**
	 * 0013/0017接口
	 * 微信支付的方法调用
	 * @param out_trade_no
	 * @param total_fee
	 * @param body
	 * @param openid
	 * @param httpRequest
	 * @return
	 */
	@RequestMapping("wxPayApi")
	@ResponseBody
	public String wxPayApi(
			@RequestParam("out_trade_no") String out_trade_no,
			@RequestParam("total_fee") int total_fee,
			@RequestParam("body") String body,
			@RequestParam("openid") String openid,
			@RequestParam("curPage") String curPage,
			HttpServletRequest httpRequest) {
		String result = null;
		try {
			//封装统一下单接口参数
			//total_fee=1;
			String nonceStr=OrderNumUtil.getNonceStr();
			String urlBody = "appid="+SysConfig.appid+"&body="+body+"&mch_id="+SysConfig.mch_id+"&nonce_str="+nonceStr+"&notify_url="+SysConfig.notify_url+"&openid="+openid+"&out_trade_no="+out_trade_no+"&spbill_create_ip="+SysConfig.spbill_create_ip+"&total_fee="+(total_fee*100)+"&trade_type="+SysConfig.trade_type;
			String md5String = urlBody+"&key="+SysConfig.wx_pay_key;
			String sign = MD5Helper.getEncoderByMd5(md5String).toUpperCase();
			String url = "<xml>"
							+ "<appid>"+SysConfig.appid+"</appid>"
							+ "<body>"+body+"</body>"
							+ "<mch_id>"+SysConfig.mch_id+"</mch_id>"
							+ "<nonce_str>"+nonceStr +"</nonce_str>"
							+ "<notify_url>"+SysConfig.notify_url+"</notify_url>"
							+ "<openid>"+openid+"</openid>"
							+ "<out_trade_no>"+out_trade_no+"</out_trade_no>"
							+ "<spbill_create_ip>"+SysConfig.spbill_create_ip+"</spbill_create_ip>"
							+ "<total_fee>"+(total_fee*100)+"</total_fee>"
							+ "<trade_type>"+SysConfig.trade_type+"</trade_type>"
							+ "<sign>"+sign+"</sign>"
						+ "</xml>";
			result = GetHelper.doHttpPost(SysConfig.unifiedorder_url, url);
			//解析返回的统一下单接口结果
			Document doc = DocumentHelper.parseText(result);
			String returnCode = doc.selectSingleNode("/xml/return_code").getText();
			String resultCode = doc.selectSingleNode("/xml/result_code").getText();
			//根据放回结果封装jsapi接口参数
			if("SUCCESS".equals(returnCode)&&"SUCCESS".equals(resultCode)){
				String appId = doc.selectSingleNode("/xml/appid").getText();
				String prepayId = "prepay_id="+doc.selectSingleNode("/xml/prepay_id").getText();
				Date now=new Date();
				String timeStamp = (now.getTime()+"").substring(0, 10);
				String resultBody = "appId="+SysConfig.appid+"&nonceStr="+nonceStr+"&package="+prepayId+"&signType=MD5&timeStamp="+timeStamp;
				String resultmd5String = resultBody+"&key="+SysConfig.wx_pay_key;
				String paySign = MD5Helper.getEncoderByMd5(resultmd5String).toUpperCase();
				result = "<xml>"
							+ "<return_code>"+returnCode+"</return_code>"
							+ "<result_code>"+resultCode+"</result_code>"
							+ "<out_trade_no>"+out_trade_no+"</out_trade_no>"
							+ "<curPage>"+curPage+"</curPage>"
							+ "<appId>"+appId+"</appId>"
							+ "<timeStamp>"+timeStamp +"</timeStamp>"
							+ "<nonce_str>"+nonceStr+"</nonce_str>"
							+ "<package>"+prepayId+"</package>"
							+ "<signType>"+SysConfig.sign_type+"</signType>"
							+ "<paySign>"+paySign+"</paySign>"
						+ "</xml>";
				//记录支付、充值记录
				transactionService.insertLogBill(openid, out_trade_no, new BigDecimal(total_fee));
			}
			logger.info("预约支付结果------"+result);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			return result;
		}
	}
	
	/**
	 * 0018接口
	 * 微信订单查询方法调用
	 * @param out_trade_no
	 * @param total_fee
	 * @param body
	 * @param openid
	 * @param httpRequest
	 * @return
	 */
	@RequestMapping("wxPayStatus")
	public String wxPayStatus(
			@RequestParam("curPage") String curPage,
			@RequestParam("out_trade_no") String out_trade_no) {
		String result = null;
		try {
			String payStatus = transactionService.queryTransactionStatus(out_trade_no);
			
			//判断是否支付
			if(ConstantConfig.TRANSACTION_NOTPAY.equals(payStatus)){
				//封装订单查询接口参数
				String nonceStr=OrderNumUtil.getNonceStr();
				String urlBody = "appid="+SysConfig.appid+"&mch_id="+SysConfig.mch_id+"&nonce_str="+nonceStr+"&out_trade_no="+out_trade_no;//+"&out_trade_no="+out_trade_no;
				String md5String = urlBody+"&key="+SysConfig.wx_pay_key;
				String sign = MD5Helper.getEncoderByMd5(md5String).toUpperCase();
				String url = "<xml>"
								+ "<appid>"+SysConfig.appid+"</appid>"
								+ "<mch_id>"+SysConfig.mch_id+"</mch_id>"
								+ "<nonce_str>"+nonceStr +"</nonce_str>"
								+ "<out_trade_no>"+out_trade_no+"</out_trade_no>"
								+ "<sign>"+sign+"</sign>"
							+ "</xml>";
				result = GetHelper.doHttpPost(SysConfig.orderQuery_url, url);
				//解析返回的订单查询接口结果
				Document doc = DocumentHelper.parseText(result);
				String returnCode = doc.selectSingleNode("/xml/return_code").getText();//result_code
				if("SUCCESS".equals(returnCode)){
					String resultCode = doc.selectSingleNode("/xml/result_code").getText();
					if("SUCCESS".equals(resultCode)){
						String tradeState = doc.selectSingleNode("/xml/trade_state").getText();
						if("SUCCESS".equals(tradeState)){
							String total_fee = doc.selectSingleNode("/xml/total_fee").getText();
							String openId = doc.selectSingleNode("/xml/openid").getText();
							String transaction_id=doc.selectSingleNode("/xml/transaction_id").getText();
							//判断是充值还是支付
							transactionService.updateTransactionStatus(openId, out_trade_no, transaction_id, new BigDecimal(total_fee));
						}
					}
				}
				logger.info("交易查询结果------"+result);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(out_trade_no.indexOf("YBXYR")!=-1){
			return "forward:/index.jsp?toPage=2";
		}else{
			return "forward:/index.jsp?toPage=1&curPage="+curPage;
		}
		
	}
	
	/**
	 * 微信支付通知
	 * @param httpRequest
	 * @param httpResponse
	 * @throws DocumentException 
	 */
	@RequestMapping("wxPayed")
	@ResponseBody
	public void wxPayed(HttpServletRequest httpRequest,HttpServletResponse httpResponse) throws Exception {
		InputStream inStream;
		try {
			inStream = httpRequest.getInputStream();
			ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = inStream.read(buffer)) != -1) {
		    	outSteam.write(buffer, 0, len);
			}
			outSteam.close();
			inStream.close();
			String result  = new String(outSteam.toByteArray(),"utf-8");//获取微信调用我们notify_url的返回信息
			Document doc = DocumentHelper.parseText(result);
			String returnCode = doc.selectSingleNode("/xml/return_code").getText();
			if("SUCCESS".equalsIgnoreCase(returnCode)){
				String outTradeNo = doc.selectSingleNode("/xml/out_trade_no").getText();
				String total_fee = doc.selectSingleNode("/xml/total_fee").getText();
				String openId = doc.selectSingleNode("/xml/openid").getText();
				String transaction_id=doc.selectSingleNode("/xml/transaction_id").getText();
				//判断是充值还是支付
				transactionService.updateTransactionStatus(openId, outTradeNo, transaction_id, new BigDecimal(total_fee));
				String returnStr="<xml>"
									+ "<return_code><![CDATA[SUCCESS]]>"
									+ "</return_code><return_msg><![CDATA[]]></return_msg>"
								+ "</xml>";
				httpResponse.getWriter().write(returnStr);   //告诉微信服务器，我收到信息了，不要在调用回调action了
			
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
//=====================================邮宝账户支付===========================================	
	/**
	 * 0019接口
	 * 邮宝账户支付的方法调用
	 * @param out_trade_no
	 * @param total_fee
	 * @param body
	 * @param openid
	 * @param httpRequest
	 * @return
	 */
	@RequestMapping("ybPayApi")
	@ResponseBody
	public  HashMap<String, Object> ybPayApi(
			@RequestParam("out_trade_no") String out_trade_no,
			@RequestParam("total_fee") int total_fee,
			@RequestParam("openid") String openid,
			@RequestParam("curPage") String curPage) {
		HashMap<String, Object> response = new HashMap<>();
		try {
			if(transactionService.ybPayTransaction(openid, out_trade_no, new BigDecimal(total_fee))){
				response.put("responseCode", "00000");
				response.put("response", ConstantConfig.PAY_SUCCESS);
				response.put("responseURL", SysConfig.notify_url_yb+curPage);
			}else{
				response.put("responseCode", "E0001");
				response.put("response", ConstantConfig.PAY_FAILED);
			}
			
		} catch (Exception e) {
			response.put("responseCode", "E0001");
			response.put("response", ConstantConfig.PAY_FAILED);
		}
		return response;
	}
	
	/**
	 * 0020接口
	 * 收入接口
	 * @param userId
	 * @param httpRequest
	 * @return
	 */
	@RequestMapping("incomeList")
	public  String incomeList(
			@RequestParam("userId") Integer userId,HttpServletRequest httpRequest) {
		try {
			List<LogIncome> incomeList=transactionService.queryIncomeList(userId);
			httpRequest.setAttribute("responseCode", "00000");
			httpRequest.setAttribute("response", ConstantConfig.QUERY_SUCCESS);
			httpRequest.setAttribute("incomeList", incomeList);
			
		} catch (Exception e) {
			e.printStackTrace();
			httpRequest.setAttribute("responseCode", "E0001");
			httpRequest.setAttribute("response", ConstantConfig.QUERY_FAILED);
		}
		return "forward:/web/person/income.jsp";
	}
	
	/**
	 * 0021接口
	 * 支出接口
	 * @param userId
	 * @param httpRequest
	 * @return
	 */
	@RequestMapping("userBillList")
	public  String userBillList(
			@RequestParam("userId") Integer userId,HttpServletRequest httpRequest) {
		try {
			List<LogNoruserbill> userBillList=transactionService.queryUserBillList(userId);
			httpRequest.setAttribute("responseCode", "00000");
			httpRequest.setAttribute("response", ConstantConfig.QUERY_SUCCESS);
			httpRequest.setAttribute("userBillList", userBillList);
			
		} catch (Exception e) {
			httpRequest.setAttribute("responseCode", "E0001");
			httpRequest.setAttribute("response", ConstantConfig.QUERY_FAILED);
		}
		return "forward:/web/person/pay.jsp";
	}
	
}